import useDrawingBoard from "@/store/modules/drawingBoard";
import { updateAreaPoint } from "@/utils/antvx6/drawArea";
import { useStorage } from "@vueuse/core";
import { cloneDeep } from "lodash-es";
const drawingBoardStore = useDrawingBoard();
/**
 * 节点单个和批量拖动
 * @param { HTMLElement }  flowGraph  antv x6 元素
 * @param { number } _width 可移动范围内画布的宽
 * @param { number } _height 可移动范围内画布的高
 */
export const addMovedNode = (flowGraph: any, _width: number, _height: number) => {
  let timer: any = null;
  let nodeList: any = [];
  // 监听节点变换事件
  let positionBeforeChange: any = [];
  flowGraph.on("node:move", ({ node, x, y }) => {
    if (node.shape === "node-point") {
      const param = {
        x,
        y,
        ...node.getData(),
      };
      positionBeforeChange.push(param);
    }
  });
  flowGraph.on("node:unselected", () => {
    positionBeforeChange = [];
  });
  flowGraph.on("node:moved", ({ node, x, y }) => {
    if (node.shape === "node-point") {
      // 获取框选的数据
      const nodeSelectedList = drawingBoardStore.nodeSelectedList;
      const { x, y } = node?.position();
      const _row = node?.getData();
      const xSum = Math.abs(x);
      const ySum = Math.abs(y);
      const widthGraph: number = Math.ceil(_width);
      const heightGraph: number = Math.ceil(_height);
      if (xSum > widthGraph || ySum > heightGraph || x < 0 || y < 0)
        return ElMessage.error(
          `您添加的画布节点【x坐标: ${x}】【y坐标: ${y}】已超出范围，规定范围是：${_width} * ${_height}内`
        );
      _row.x = x;
      _row.y = y;
      if (nodeSelectedList.length > 3) {
        nodeList.push(_row);
        timer && clearTimeout(timer);
        timer = setTimeout(() => {
          // const listPromise = nodeList.map((item: any) => {
          //   return getNodes(item, mapId, false);
          // });
          // Promise.all(listPromise).finally(() => {
          //   canvansMapStore.changeNodes("node");
          //   nodeList = [];
          // });
          nodeList = [];
        }, 500);
      } else {
        const message = `是否移动【 ${_row.nodeNameEn} 】节点坐标： ( x:  ${x} , y:  ${y} ) , 移动后是否提交此操作?`;
        ElMessageBox.confirm(`${message}`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
          })
          .catch(() => {
            const data: any = useStorage("extractGraphObj", null);
            const renderObj = cloneDeep(JSON.parse(data.value));
            const findNode = renderObj.nodes.find((item: any) => item.id === _row.nodeNameEn);
            if (findNode) {
              node.position(findNode.dataStorage.x, findNode.dataStorage.y);
              node.setData({
                x: findNode.dataStorage.x,
                y: findNode.dataStorage.y,
              });
            }
          });
      }
    } else if(node.shape === "node-area") {
      updateAreaPoint(node)
    }
  });
};
